const { Model, DataTypes } = require('sequelize');
const User = require('./User');
const Question = require('./Question');
const sequelize = require('../db/db');

class WrongQuestion extends Model { }
WrongQuestion.init(
  {
    id: {
      type: DataTypes.CHAR(18),
      primaryKey: true,
      allowNull: false,
      comment: '错题记录ID'
    },
    user_id: {
      type: DataTypes.CHAR(18),
      allowNull: false,
      references: { model: User, key: 'user_id' }
    },
    question_id: {
      type: DataTypes.CHAR(18),
      allowNull: false,
      references: { model: Question, key: 'id' }
    },
    error_count: {
      type: DataTypes.INTEGER,
      defaultValue: 1
    },
    last_wrong_time: DataTypes.DATE
  },
  {
    sequelize,
    modelName: 'WrongQuestion',
    tableName: 'wrong_question',
    timestamps: false,
    indexes: [
      {
        unique: true,
        fields: ['id']
      },
      {
        fields: ['user_id', 'question_id']
      }
    ]
  }
);

// 建立关联关系
WrongQuestion.belongsTo(User, {
  foreignKey: 'user_id',
  targetKey: 'user_id',
  as: 'user'
});

WrongQuestion.belongsTo(Question, {
  foreignKey: 'question_id',
  targetKey: 'id',
  as: 'question'
});

module.exports = WrongQuestion;